
module.exports = {
  insert (CollectionName, insertData) {
    return new Promise((resolve, reject) => {
      // node 错误优先回调原则
      CollectionName.insertMany(insertData, (err) => {
        if (err) throw err;
        resolve()
      })
    })
  },
  delete (CollectionName, whereData, deleteNum) {
    return new Promise(resolve => {
      const deleteType = deleteNum === 1 ? 'deleteMany' : 'deleteOne'
      CollectionName[deleteType](whereData, err => {
        if (err) throw err;
        resolve()
      })
    })
  },
  update (CollectionName, whereData, updateData, updateNum) {
    return new Promise(resolve => {
      const updateType = updateNum === 1 ? 'updateMany' : 'updateOne'
      CollectionName[updateType](whereData, updateData, err => {
        if (err) throw err;
        resolve()
      })
    })
  },
  find (CollectionName, whereData, showData) {
    return new Promise(resolve => {
      CollectionName.find(whereData, showData).exec((err, data) => {
        if (err) throw err;
        resolve(data)
      })
    })
  },
  paging (CollectionName, whereData, showData, count, limitNum) {
    limitNum = limitNum || 10 
    count = count || 1
    return new Promise(resolve => {
      // 页码 不是从0  开始， 是从1开始，所以要减1
      CollectionName.find(whereData, showData).limit(limitNum).skip((count - 1) * limitNum).exec((err, data) => {
        if (err) throw err
        resolve(data)
      })
    })
  },
  count (CollectionName, whereData) {
    whereData = whereData || {}
    return new Promise(resolve => {
      // count() 在某些 版本 不可用
      // countDocuments() ok
      // estimatedDocumentCount() ok
      CollectionName.find(whereData).estimatedDocumentCount((err, len) => {
        if (err) throw err
        resolve(len)
      })
    })
  },
  distinct(CollectionName, type) {
    return new Promise((resolve) => {
      CollectionName.distinct(type).exec((err, data) => {
        if (err) throw err
        resolve(data)
      })
    })
  },
  sort (CollectionName, whereData, showData, sortData) {
    return new Promise((resolve) => {
      CollectionName.find(whereData, showData).sort(sortData).exec((err, data) => {
        if (err) throw err
        resolve(data)
      })
    })
  }
}